package com.example.zzx.dovebook.main.booksea.recommendation

import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.baselibrary.widget.LoadingStateView
import com.example.dovebookui.widget.BookSeaDecoration
import com.example.library.BaseAdapter
import com.example.zzx.dovebook.R
import com.example.zzx.dovebook.base.BaseFragment
import com.example.zzx.dovebook.base.CommonRepository
import com.example.zzx.dovebook.base.UserContext
import com.example.zzx.dovebook.base.ValueWrapper.*
import com.example.zzx.dovebook.login.LoginCheck
import com.example.zzx.dovebook.user.UserManager
import com.example.zzx.heartanimation.LikeLayout
import kotlinx.android.synthetic.main.fragment_polular_recommendation.*

class PopularFragment : BaseFragment<PopularViewModel>(), UserContext {

    private lateinit var adapter: BaseAdapter

    private lateinit var loadMoreView: LoadingStateView
    private lateinit var emptyView: LoadingStateView

    override fun createViewModel(): Class<PopularViewModel>? = PopularViewModel::class.java

    override fun createRepository(): Any {
        return CommonRepository()
    }

    override fun getLayoutId(): Int = R.layout.fragment_polular_recommendation

    override fun initViews() {

        setupRecyclerView()

        refreshLayout.setOnRefreshListener {
            queryHotBookShare(true)
        }
    }

    private fun setupRecyclerView() {

        emptyView = LoadingStateView(activity)
        emptyView.setOnRetryListener {
            emptyView.loading()
            queryHotBookShare(false)
        }

        loadMoreView = LoadingStateView(activity)
        loadMoreView.setOnRetryListener {
            loadMoreView.loading()
            queryHotBookShare(false)
        }
        adapter = BaseAdapter.Builder()
            .emptyView(emptyView)
            .addRooter(loadMoreView)
            .autoLoadMore()
            .build()
        adapter.setOnLoadMoreListener {
            if (!loadMoreView.isLoading) return@setOnLoadMoreListener
            queryHotBookShare(false)
        }
        adapter.emptyState()
        //不能将此属性设置为false否则嵌套滑动的时候不能通知到Behavior
        //recyclerView.isNestedScrollingEnabled = true
        recyclerView.addItemDecoration(BookSeaDecoration())
        recyclerView.layoutManager = GridLayoutManager(activity, 2, RecyclerView.VERTICAL, false).apply {
            spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                /**
                 * 返回值表示这个item占据计算好的item数量,如果想要占满一行，
                 * 则此item应该占据spanCount个
                 */
                override fun getSpanSize(position: Int): Int {
                    return if (adapter.itemCount == position + 1) spanCount else 1
                }
            }
        }
        recyclerView.adapter = adapter
    }

    override fun initOptions() {
        queryHotBookShare(true)
    }

    private fun queryHotBookShare(isUpdate: Boolean) {
        val lastItemCreateAt = if (adapter.dataCount == 0 || isUpdate) System.currentTimeMillis()
        else {
            (adapter.lastItem as ListBookShare).bookShare.createAt
        }
        val userId = UserManager.getInstance(activity).loginUserId ?: ""
        if (isUpdate) {
            refreshLayout.isRefreshing = true
            loadMoreView.loading()
        }
        viewModel.queryHotBookShare(this, userId, lastItemCreateAt).observe(this, Observer {
            if (isUpdate) refreshLayout.isRefreshing = false
            when (it.type) {
                TYPE_FAILED -> {
                    if (adapter.isInEmptyState) {
                        emptyView.failed()
                    } else if (!isUpdate) {
                        loadMoreView.failed()
                    }
                }
                TYPE_NO_CONTENT -> {
                    if (adapter.isInEmptyState) {
                        emptyView.empty()
                    } else if (!isUpdate) {
                        loadMoreView.noMore()
                    }
                }
                TYPE_NORMAL -> {
                    adapter.apply {
                        if (isInEmptyState) cancelEmptyState()
                        if (isUpdate) {
                            adapter.replace(it.value as List<ListBookShare>)
                        }
                        else {
                            add(it.value as List<ListBookShare>)
                        }

                    }
                }
            }
        })
    }

    /**
     * 点赞
     */
    @LoginCheck
    override fun bookShareLike(listBookShare: ListBookShare, targetView: LikeLayout, bookShareId: String) {
        viewModel.bookShareLike(bookShareId, UserManager.getInstance(activity).loginUserId ?: "")
            .observe(this, Observer { success ->
                if (success) listBookShare.updateLike(targetView)
            })
    }

    @LoginCheck
    override fun cancelBookShareLike(listBookShare: ListBookShare, targetView: LikeLayout, bookShareId: String) {
        viewModel.cancelBookShareLike(bookShareId, UserManager.getInstance(activity).loginUserId ?: "")
            .observe(this, Observer { success ->
                if (success) listBookShare.updateCancelLike(targetView)
            })
    }

}